import psutil
import time
import datetime

"""
2018.10.26
预计简化程序，
    简化字符串形式，"i min [rate][use_in_a_min][use_all_min]"
    简化open_write的调用，组织好字符串后统一写入文件
    简化程序结构，重构函数主体
"""


def network_speed():
    """import psutil，time
    Network speed. Unit = ** Kb/s"""
    sent_a = psutil.net_io_counters().bytes_sent
    recv_a = psutil.net_io_counters().bytes_recv
    time.sleep(1)
    sent_b = psutil.net_io_counters().bytes_sent
    recv_b = psutil.net_io_counters().bytes_recv
    print(f"上行{round((sent_b-sent_a)/Download1024,2)}kb/s，下行{round((recv_b-recv_a)/Download1024,2)}kb/s")
    return recv_b - recv_a


def count(data_b=None, data_e=None):
    if data_e or data_b is None:
        return 0, 0
    sent = round(((data_e[0] - data_b[0]) / (60 * 1024)), 2)
    recv = round(((data_e[1] - data_b[1]) / (60 * 1024)), 2)
    return sent, recv


def network_amount_now() -> object:
    """import psutil，time
    Network amount. Unit = ** Kb; 得到当前时间的数据量"""
    sent_a = psutil.net_io_counters().bytes_sent
    recv_a = psutil.net_io_counters().bytes_recv
    return sent_a, recv_a


def network_minute():
    """
    计算60s内的网速，流量
    :return: str(up_rate, down_rate, up_use, down_use)
    """
    first = network_amount_now()
    time.sleep(60)
    last = network_amount_now()
    sent_use_level = round(((last[0] - first[0]) / (1024 * 1024)), 4)
    recv_use_level = round(((last[1] - first[1]) / (1024 * 1024)), 4)
    sent_rate = round(((last[0] - first[0]) / (60 * 1024)), 2)
    recv_rate = round(((last[1] - first[1]) / (60 * 1024)), 2)
    result_rate = f"[up_rate：{sent_rate}kb/s down_rate：{recv_rate}kb/s]"
    result_use = f"[up_use:{sent_use_level}Mb down_use:{recv_use_level}Mb]"
    result = result_rate + result_use
    return result


def open_write(content):
    """
    This function get a string and write into a file.
    :param content: string
    :return: None
    """
    content = str(content)
    with open("./Log_test.txt", "a", encoding="utf-8") as log:
        log.write(content)


if __name__ == "__main__":
    with open("./Log_test.txt", "a", encoding="utf-8") as log1:
        log1.write("\n")
        log1.write("*" * 50)
        log1.write("\n开始时间：\t")
        time_begin = time.time()
        log1.write(datetime.datetime.now().strftime("%Y-%m-%d  %H:%M:%S"))
        log1.write("\n")
        begin = network_amount_now()
        cycle = 1

    while True:
        # 每分钟写入一次网速
        open_write(f"{cycle}min\t")
        open_write(f'[{datetime.datetime.now().strftime("%H:%M")}]')
        open_write(network_minute())
        # open_write("\n")
        end = network_amount_now()
        counter = count(begin, end)
        open_write(f"累计上行数据:{counter[0]}Mb({round(counter[0]/(Download1024*8),4)}Gb)\t"
                   f"下行数据：{round(counter[1], 4)}Mb({round(counter[1]/(Download1024*8),4)}Gb)\n")
        cycle += 1

    time_end = time.time()
    # time_course = (time_end - time_begin)
    # time_course = datetime.datetime.fromtimestamp(time.localtime(time_course))

    counter = count(begin, end)
    open_write(f"历时{cycle}min,已上行数据:{counter[0]}Mb\t下行数据：{counter[1]}Mb\n\n\n")
